package com.chongzi.cloud;

import java.util.Arrays;
import java.util.concurrent.ThreadLocalRandom;

public class code215 {
    public static void main(String[] args) {
        int[] data = {3,2,1,5,6,4};
        int k=findKthLargest(data,2);
        System.out.println(k );

    }
    public static int findKthLargest(int[] nums, int k) {
        int kBig=-1;
        qsort(nums,0,nums.length-1);
        kBig=nums[nums.length-k+1];
        return kBig;

    }

    private static void qsort(int[] nums, int left, int right) {
        if (left>right){
            return ;
        }
        int pivotIndex=partition(nums,left,right);
        qsort(nums,left,pivotIndex-1);
        qsort(nums,pivotIndex+1,right);
    }

    private static int partition(int[] nums, int left, int right) {
         int idx= ThreadLocalRandom.current().nextInt(right-left+1)+left;
         swap(nums,left,idx);
         int pv=nums[left];
         int i=left+1;
         int j=right;
         while (i<=j){
             while (i<=j&&nums[i]<pv){
                 i++;
             }
             while (i<=j&&nums[j]>pv){
                 j--;
             }
             if (i<=j){
                 swap(nums,i,j);
                 i++;
                 j--;
             }
         }
         swap(nums,left,j);
         return j;

    }

    private static void swap(int[] nums, int left, int idx) {
        int temp=nums[left];
        nums[left]=nums[idx];
        nums[idx]=temp;
    }


}
